Skip to content

Implement outbound email sending - #4

Merged
KMKoushik merged 4 commits into
mainfrom
feat/messages-send
Mar 8, 2026
Merged

KMKoushik merged 4 commits into
mainfrom
feat/messages-send

Conversation

@KMKoushik

@KMKoushik KMKoushik commented Mar 8, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • implement the messages.send pipeline with inbox ownership checks, payload validation, Cloudflare EMAIL.send() delivery, thread linkage, and D1 persistence for accepted and failed outbound messages
  • add outbound send integration tests covering happy path, ownership rejection, validation, provider failure mapping, reply headers, and persisted send results
  • update mvp.md to strike through the MVP items completed through the send pipeline

Validation

  • pnpm test -- src/lib/email/outbound.test.ts
  • pnpm test
  • pnpm exec tsc --noEmit
  • pnpm build

Summary by CodeRabbit

  • New Features

    • End-to-end outbound email sending with validation, threading, reply headers, and size/recipient limits.
    • Delivery events for accepted and failed sends.
  • API

    • New send-message endpoint with input/output validation and mapped error responses.
  • Tests

    • Comprehensive outbound tests and a test harness with deterministic failure injection.
  • Chores

    • CI workflow added for pull-request validation.
  • Refactor

    • Centralized runtime/db access and simplified inbox/email helper interfaces.
  • Documentation

    • Multiple prior MVP capabilities marked deprecated.

@coderabbitai

coderabbitai Bot commented Mar 8, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: abea42c0-cfa1-4481-8bdd-c82d81256f87

📥 Commits

Reviewing files that changed from the base of the PR and between 8437977 and 51b92d3.

📒 Files selected for processing (3)
  • src/lib/email/outbound.test.ts
  • src/lib/email/outbound.ts
  • src/orpc/procedures/messages.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/lib/email/outbound.test.ts
  • src/lib/email/outbound.ts

📝 Walkthrough

Walkthrough

Adds a complete outbound email pipeline (validation, threading, provider send, persistence, oversized-body storage, and events), expands email event types, introduces test-harness fault injection and outbound tests, replaces a placeholder ORPC messages router with a send route, and converts many MVP doc items to struck-through.

Changes

Cohort / File(s) Summary
Documentation
mvp.md
Marks many MVP requirements, API lines, inbound/outbound flows, event types, and acceptance criteria as struck-through (deprecated).
Email Events
src/lib/email/events.ts
Adds MessageSentAcceptedEvent and MessageSentFailedEvent, extends EmailEvent union, and adds factory creators.
Outbound Email Logic
src/lib/email/outbound.ts
New end-to-end sendMessage implementation: input validation, ownership checks, threading, headers, provider send, provider error mapping, persistence, R2 storage for large bodies, event emission, and exported constants/types/errors.
Outbound Tests
src/lib/email/outbound.test.ts
Comprehensive test suite covering success, authorization, validation, provider failures, reply threading, DB state, sent payloads, and queue events using the email test harness.
Email Test Harness
src/lib/email/test-harness.ts, src/lib/email/test-harness.test.ts
Adds EMAIL binding with deterministic fault injection (failWith) and updates tests to mock runtime to guard against unintended runtime calls.
Inbound Email
src/lib/email/inbound.ts, src/lib/email/inbound.test.ts
handleInboundEmail no longer accepts env; it obtains getWorkerEnv()/getDb() internally. Tests updated to use hoisted harness and mocked runtime.
Inboxes API / Lib
src/lib/email/inboxes.ts, src/orpc/procedures/inboxes.ts
Switched from DB-passed helpers to runtime accessors: removed db parameter from inbox functions and callers now use new signatures that call getDb() internally.
Runtime & DB client
src/lib/runtime.ts, src/db/client.ts
Adds src/lib/runtime.ts that initializes and exports singleton db, getDb(), and getWorkerEnv(); src/db/client.ts now re-exports db/getDb from runtime.
ORPC Messages Route
src/orpc/procedures/messages.ts
Replaces placeholder router with a send route that validates input, calls sendMessage, and maps send errors to HTTP codes.
Worker Changes
src/worker.ts
Stops passing env into inbound handler (now internal) and suppresses unused param.
CI
.github/workflows/ci.yml
Adds PR validation workflow: checkout, pnpm/node setup, migrations, tests, typecheck, and build.

Sequence Diagram

sequenceDiagram
    participant Client
    participant API as API Route\n(messages.ts)
    participant Module as Outbound Module\n(outbound.ts)
    participant DB as Database
    participant Email as Provider\n(EMAIL)
    participant Events as Event Queue\n(EMAIL_EVENTS)
    participant Storage as R2 Storage\n(EMAIL_STORAGE)

    Client->>API: POST /messages/send
    API->>Module: sendMessage(userId, input)
    
    Module->>Module: Validate input\n(recipient limits, body size)
    Module->>DB: Resolve inbox ownership\n& find/create thread
    DB-->>Module: Inbox + Thread info
    
    rect rgba(100, 150, 200, 0.5)
        Note over Module: Build message context\ncompute IDs, headers, reply context
        Module->>Email: send(message with headers)
    end
    
    alt Success
        Email-->>Module: providerMessageId
        Module->>Storage: Put oversized body (if needed)
        Storage-->>Module: Stored reference
        Module->>DB: Insert message + update thread
        DB-->>Module: Persisted
        Module->>Events: Emit MessageSentAccepted
        Events-->>Module: Queued
    else Failure
        Email-->>Module: Error
        Module->>DB: Persist failure state with errorCode/message
        DB-->>Module: Persisted
        Module->>Events: Emit MessageSentFailed
        Events-->>Module: Queued
    end
    
    Module-->>API: SendMessageResult
    API-->>Client: 200 OK or error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I stitched the threads and queued a song,

A MessageSent accepted, then fixed when wrong,
R2 cradled bodies too large for lips,
Tests hopped in, asserting headers and flips,
I nibble logs and toss confetti on the logs.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: implementing outbound email sending functionality. It directly corresponds to the primary purpose of the pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/messages-send

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/orpc/procedures/messages.ts (1)

16-25: Prefer a shared output schema here.

sendMessageResultSchema is hand-maintained while sendMessage() defines the real payload. Exporting one schema from the outbound module keeps the oRPC contract from drifting the next time the send result changes. Based on learnings: Keep oRPC schema and handlers aligned when changing contracts.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/orpc/procedures/messages.ts` around lines 16 - 25, The
sendMessageResultSchema defined here is duplicating the actual send result used
by sendMessage(); stop hand-maintaining a separate schema and instead
import/export the single shared output schema from the outbound module so the
oRPC contract stays in sync. Replace the local sendMessageResultSchema with an
import of the authoritative schema exported by the outbound code (the schema
used by sendMessage()), update any references in this file to use that exported
symbol, and export it if this module needs to re-expose the same name so callers
continue to work.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/lib/email/outbound.ts`:
- Around line 133-243: Persist the outbound message before calling the
non-idempotent env.EMAIL.send: write the oversized body to EMAIL_STORAGE (if
bodyStorage.oversizedBodyR2Key), then inside database.transaction insert the
emailMessages row with status 'pending' (or 'sending'), null providerMessageId
and sentAt; after the transaction call env.EMAIL.send (the existing EMAIL.send
call), capture providerMessageId and map errors, then update the emailMessages
row (update providerMessageId, status='accepted' and sentAt on success or
status='failed' + errorCode/errorMessage on failure) and finally emit events
(env.EMAIL_EVENTS.send) based on the updated status; use the same
messageId/threadId/internetMessageId and reuse functions/symbols from this diff
(EMAIL.send, EMAIL_STORAGE.put, database.transaction, emailMessages
insert/update, createMessageSentAcceptedEvent/createMessageSentFailedEvent) so
retries won’t create duplicate outbound sends or leave missing local records.
- Around line 280-296: getReplyContext currently includes every
emailMessages.internetMessageId in the thread, which pulls in synthetic IDs for
failed outbound sends; change the database query that builds threadMessages to
exclude failed outbound rows by adding conditions on emailMessages.direction and
emailMessages.status (e.g., include rows where direction = 'inbound' OR
direction = 'outbound' AND status IN ('sent','accepted','delivered') or your
project's equivalent status flags) so only inbound or accepted/outgoing messages
contribute to references; update the mapping that builds references from
threadMessages.internetMessageId accordingly and add a regression test that
simulates a failed outgoing send and then a retry to ensure the retry does not
set In-Reply-To/References to the failed message ID.

---

Nitpick comments:
In `@src/orpc/procedures/messages.ts`:
- Around line 16-25: The sendMessageResultSchema defined here is duplicating the
actual send result used by sendMessage(); stop hand-maintaining a separate
schema and instead import/export the single shared output schema from the
outbound module so the oRPC contract stays in sync. Replace the local
sendMessageResultSchema with an import of the authoritative schema exported by
the outbound code (the schema used by sendMessage()), update any references in
this file to use that exported symbol, and export it if this module needs to
re-expose the same name so callers continue to work.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 39fa80f6-73a9-485e-a603-ee8999cf02d0

📥 Commits

Reviewing files that changed from the base of the PR and between 02f6e75 and 83d7231.

📒 Files selected for processing (6)
  • mvp.md
  • src/lib/email/events.ts
  • src/lib/email/outbound.test.ts
  • src/lib/email/outbound.ts
  • src/lib/email/test-harness.ts
  • src/orpc/procedures/messages.ts

Comment thread src/lib/email/outbound.ts Resolved
Comment thread src/lib/email/outbound.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
.github/workflows/ci.yml (3)

3-4: Consider specifying PR event types for clarity.

The pull_request trigger without explicit types defaults to opened, synchronize, and reopened, which is typically sufficient. If this is intentional, no change needed. Otherwise, consider being explicit:

on:
  pull_request:
    types: [opened, synchronize, reopened]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/ci.yml around lines 3 - 4, The workflow's GitHub Actions
trigger uses the generic pull_request event; update the on: pull_request block
to explicitly declare desired event types (e.g., types: [opened, synchronize,
reopened]) to make the trigger behavior explicit and avoid accidental
runs—modify the pull_request configuration in the CI workflow so it includes a
types list under pull_request.

6-10: Add a job timeout to prevent runaway workflows.

Without a timeout, the job can hang indefinitely if a step stalls, consuming CI minutes.

⏱️ Proposed fix to add timeout
 jobs:
   validate:
     runs-on: ubuntu-latest
+    timeout-minutes: 15
     permissions:
       contents: read
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/ci.yml around lines 6 - 10, Add a timeout to the validate
job to prevent runaway workflows by adding a timeout-minutes setting under the
job definition for validate (the jobs: validate: block). Modify the validate job
configuration to include a sensible timeout-minutes value (e.g., 30) so the
workflow runner cancels the job if it exceeds that duration; ensure the
timeout-minutes key is at the same indentation level as runs-on and permissions
within the validate job.

30-34: Clarify the purpose of the migration list step.

Running db:migrate:list after db:migrate is confusing—if the intent is to verify no pending migrations remain, consider failing the step when migrations are still pending. Otherwise, if this is purely informational, consider moving it before db:migrate to show what will be applied, or remove it if it adds no value.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/ci.yml around lines 30 - 34, The "Check pending local
migrations" step currently runs pnpm db:migrate:list after pnpm db:migrate but
doesn't fail the job if migrations remain; change this step (named "Check
pending local migrations") to explicitly verify there are no pending migrations
and fail CI when there are: run pnpm db:migrate:list and exit non-zero if its
output indicates pending migrations (or call a small script/npm script that
parses pnpm db:migrate:list output and returns non-zero on pending items) so the
pipeline enforces that pnpm db:migrate left the DB up-to-date.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In @.github/workflows/ci.yml:
- Around line 3-4: The workflow's GitHub Actions trigger uses the generic
pull_request event; update the on: pull_request block to explicitly declare
desired event types (e.g., types: [opened, synchronize, reopened]) to make the
trigger behavior explicit and avoid accidental runs—modify the pull_request
configuration in the CI workflow so it includes a types list under pull_request.
- Around line 6-10: Add a timeout to the validate job to prevent runaway
workflows by adding a timeout-minutes setting under the job definition for
validate (the jobs: validate: block). Modify the validate job configuration to
include a sensible timeout-minutes value (e.g., 30) so the workflow runner
cancels the job if it exceeds that duration; ensure the timeout-minutes key is
at the same indentation level as runs-on and permissions within the validate
job.
- Around line 30-34: The "Check pending local migrations" step currently runs
pnpm db:migrate:list after pnpm db:migrate but doesn't fail the job if
migrations remain; change this step (named "Check pending local migrations") to
explicitly verify there are no pending migrations and fail CI when there are:
run pnpm db:migrate:list and exit non-zero if its output indicates pending
migrations (or call a small script/npm script that parses pnpm db:migrate:list
output and returns non-zero on pending items) so the pipeline enforces that pnpm
db:migrate left the DB up-to-date.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 754f9a42-6925-4d16-93d7-800c85ee8bb5

📥 Commits

Reviewing files that changed from the base of the PR and between 83d7231 and b5dfaaf.

📒 Files selected for processing (1)
  • .github/workflows/ci.yml

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/lib/email/inboxes.ts (1)

156-192: ⚠️ Potential issue | 🟡 Minor

Potential TOCTOU race condition in alias uniqueness check.

The check for existing alias (lines 171-184) and the subsequent update (lines 187-190) are not atomic. Under concurrent requests, two users could both pass the uniqueness check before either update completes, potentially resulting in duplicate aliases.

The database has a unique index on customLocalPart (from schema), which will prevent actual duplicates at the DB level, but the current code would throw a less descriptive database constraint error rather than the friendly InboxAliasConflictError.

Consider wrapping the check and update in a transaction, or catching the unique constraint violation and re-throwing as InboxAliasConflictError.

🛡️ Suggested fix using transaction
 export async function updateInboxAliasForUser(
   userId: string,
   inboxId: string,
   alias: string | null,
 ) {
   const nextDb = getDb()
   const inbox = await getInboxForUser(userId, inboxId)

   if (!inbox) {
     return null
   }

   const normalizedAlias = alias === null ? null : validateInboxAlias(alias)

-  if (normalizedAlias) {
-    const [existingAlias] = await nextDb
-      .select({ id: inboxes.id })
-      .from(inboxes)
-      .where(
-        and(
-          eq(inboxes.customLocalPart, normalizedAlias),
-          ne(inboxes.id, inboxId),
-        ),
-      )
-      .limit(1)
-
-    if (existingAlias) {
-      throw new InboxAliasConflictError('That inbox alias is already taken.')
+  try {
+    if (normalizedAlias) {
+      const [existingAlias] = await nextDb
+        .select({ id: inboxes.id })
+        .from(inboxes)
+        .where(
+          and(
+            eq(inboxes.customLocalPart, normalizedAlias),
+            ne(inboxes.id, inboxId),
+          ),
+        )
+        .limit(1)
+
+      if (existingAlias) {
+        throw new InboxAliasConflictError('That inbox alias is already taken.')
+      }
     }
-  }
-
-  await nextDb
-    .update(inboxes)
-    .set({ customLocalPart: normalizedAlias })
-    .where(and(eq(inboxes.userId, userId), eq(inboxes.id, inboxId)))
+
+    await nextDb
+      .update(inboxes)
+      .set({ customLocalPart: normalizedAlias })
+      .where(and(eq(inboxes.userId, userId), eq(inboxes.id, inboxId)))
+  } catch (error) {
+    // Handle unique constraint violation from race condition
+    if (error instanceof Error && error.message.includes('UNIQUE constraint failed')) {
+      throw new InboxAliasConflictError('That inbox alias is already taken.')
+    }
+    throw error
+  }

   return getInboxForUser(userId, inboxId)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/inboxes.ts` around lines 156 - 192, The uniqueness check and
update in updateInboxAliasForUser (using getDb(), validateInboxAlias,
getInboxForUser, and inboxes) must be made atomic: either perform the
select-and-update inside a database transaction so the existence check and
nextDb.update(...) occur together, or keep the current flow but catch the DB
unique constraint error thrown by the update (the unique index on
inboxes.customLocalPart) and re-throw it as InboxAliasConflictError('That inbox
alias is already taken.'); ensure you reference the inboxes table and convert
the DB constraint error to the friendly error before returning getInboxForUser.
♻️ Duplicate comments (1)
src/lib/email/outbound.ts (1)

273-289: ⚠️ Potential issue | 🟠 Major

Exclude failed outbound messages from reply references.

getReplyContext includes all messages in the thread regardless of status. Failed outbound messages still have a synthetic internetMessageId, so replies could reference a message the remote server never received, potentially breaking threading.

Filter to only include successfully delivered messages:

🔧 Suggested fix
   const threadMessages = await database
     .select({
       internetMessageId: emailMessages.internetMessageId,
+      status: emailMessages.status,
     })
     .from(emailMessages)
     .where(and(eq(emailMessages.threadId, threadId), eq(emailMessages.inboxId, inboxId)))
     .orderBy(asc(emailMessages.createdAt), asc(emailMessages.id))

   const references = threadMessages
+    .filter((message) => message.status === 'received' || message.status === 'accepted')
     .map((message) => message.internetMessageId)
     .filter((value): value is string => Boolean(value))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/outbound.ts` around lines 273 - 289, getReplyContext is
including messages regardless of delivery status so replies may reference
synthetic internetMessageId values for failed outbound sends; update the query
that builds threadMessages (the select from emailMessages filtered by threadId
and inboxId) to exclude failed/undelivered messages by adding a status filter on
emailMessages (e.g., only include statuses that indicate successful delivery
such as "sent"/"delivered" or use a notIn([...failedStatuses]) condition), then
build references from those filtered messages (still using
emailMessages.internetMessageId, threadId, inboxId) so inReplyTo and references
only point to actually delivered messages.
🧹 Nitpick comments (3)
src/lib/email/outbound.ts (1)

125-144: Consider persist-before-send for idempotency.

The current flow calls EMAIL.send() before persisting to the database. If EMAIL.send() succeeds but a subsequent step (R2 write or DB transaction) fails, the email is delivered but no local record exists—client retries could duplicate the send.

An alternative is to insert a pending row first, attempt delivery, then update to accepted/failed. This makes retries idempotent (check for existing pending/accepted row with same idempotency key). This is a tradeoff between complexity and resilience; flagging for consideration.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/outbound.ts` around lines 125 - 144, The send flow currently
calls env.EMAIL.send() before persisting the outbound record, which can lead to
duplicate deliveries if the DB/R2 write fails; change the flow in outbound.ts to
create a pending DB row first (with the same internetMessageId/idempotency key
and fields used in buildOutboundHeaders/replyContext), then call EMAIL.send(),
capture result.messageId into providerMessageId, and finally update the pending
row status to 'accepted' or to 'failed' using the mapped error (mappedError.code
/ mappedError.message) on catch; ensure the update path is idempotent by
checking for an existing pending/accepted row and using the
internetMessageId/idempotency key to avoid double sends.
src/lib/email/outbound.test.ts (1)

213-256: Consider adding a regression test for failed-send retry.

The threading test validates In-Reply-To and References headers for successful sends. To guard against the getReplyContext issue (failed sends leaking into references), consider adding a test that:

  1. Sends a message that fails at the provider
  2. Sends a successful reply
  3. Asserts the reply's References header excludes the failed message's internetMessageId
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/outbound.test.ts` around lines 213 - 256, Add a regression test
that simulates a failed provider send and verifies reply headers don’t include
the failed send’s internetMessageId: use sendMessage to create a first message
but simulate a provider failure for that send (so it fails to set or persist
internetMessageId), then send a successful reply via sendMessage with
replyToThreadId set to the firstResult.threadId, query emailMessages for the
successful reply and assert harness.email.sent for that reply does NOT include
the failed message’s internetMessageId in References/In-Reply-To while still
threading to the same threadId; reference sendMessage, getReplyContext (where
the bug manifests), emailMessages, harness.email.sent, and internetMessageId to
locate relevant logic to exercise and assert.
src/lib/email/inboxes.ts (1)

8-29: Reserved aliases list includes appropriate entries.

The reserved aliases cover standard email addresses (postmaster, abuse, support, etc.) and product-specific terms. Note that koushik and kdawg appear to be personal reservations - consider documenting their purpose or moving them to configuration if they're user-specific.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/email/inboxes.ts` around lines 8 - 29, RESERVED_INBOX_ALIASES
currently contains two personal aliases ("koushik" and "kdawg"); remove these
from the hard-coded Set and either document them or move them to a configurable
source (env/config) so repository-wide reserved names are generic; update any
references to RESERVED_INBOX_ALIASES to read from the new configuration or
fallback to the existing Set without the personal entries, and add a brief
comment explaining where personal/team-specific aliases should be configured.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/lib/email/inboxes.ts`:
- Around line 156-192: The uniqueness check and update in
updateInboxAliasForUser (using getDb(), validateInboxAlias, getInboxForUser, and
inboxes) must be made atomic: either perform the select-and-update inside a
database transaction so the existence check and nextDb.update(...) occur
together, or keep the current flow but catch the DB unique constraint error
thrown by the update (the unique index on inboxes.customLocalPart) and re-throw
it as InboxAliasConflictError('That inbox alias is already taken.'); ensure you
reference the inboxes table and convert the DB constraint error to the friendly
error before returning getInboxForUser.

---

Duplicate comments:
In `@src/lib/email/outbound.ts`:
- Around line 273-289: getReplyContext is including messages regardless of
delivery status so replies may reference synthetic internetMessageId values for
failed outbound sends; update the query that builds threadMessages (the select
from emailMessages filtered by threadId and inboxId) to exclude
failed/undelivered messages by adding a status filter on emailMessages (e.g.,
only include statuses that indicate successful delivery such as
"sent"/"delivered" or use a notIn([...failedStatuses]) condition), then build
references from those filtered messages (still using
emailMessages.internetMessageId, threadId, inboxId) so inReplyTo and references
only point to actually delivered messages.

---

Nitpick comments:
In `@src/lib/email/inboxes.ts`:
- Around line 8-29: RESERVED_INBOX_ALIASES currently contains two personal
aliases ("koushik" and "kdawg"); remove these from the hard-coded Set and either
document them or move them to a configurable source (env/config) so
repository-wide reserved names are generic; update any references to
RESERVED_INBOX_ALIASES to read from the new configuration or fallback to the
existing Set without the personal entries, and add a brief comment explaining
where personal/team-specific aliases should be configured.

In `@src/lib/email/outbound.test.ts`:
- Around line 213-256: Add a regression test that simulates a failed provider
send and verifies reply headers don’t include the failed send’s
internetMessageId: use sendMessage to create a first message but simulate a
provider failure for that send (so it fails to set or persist
internetMessageId), then send a successful reply via sendMessage with
replyToThreadId set to the firstResult.threadId, query emailMessages for the
successful reply and assert harness.email.sent for that reply does NOT include
the failed message’s internetMessageId in References/In-Reply-To while still
threading to the same threadId; reference sendMessage, getReplyContext (where
the bug manifests), emailMessages, harness.email.sent, and internetMessageId to
locate relevant logic to exercise and assert.

In `@src/lib/email/outbound.ts`:
- Around line 125-144: The send flow currently calls env.EMAIL.send() before
persisting the outbound record, which can lead to duplicate deliveries if the
DB/R2 write fails; change the flow in outbound.ts to create a pending DB row
first (with the same internetMessageId/idempotency key and fields used in
buildOutboundHeaders/replyContext), then call EMAIL.send(), capture
result.messageId into providerMessageId, and finally update the pending row
status to 'accepted' or to 'failed' using the mapped error (mappedError.code /
mappedError.message) on catch; ensure the update path is idempotent by checking
for an existing pending/accepted row and using the internetMessageId/idempotency
key to avoid double sends.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9c343db8-2155-48ea-ad6d-bf20c85e2a9e

📥 Commits

Reviewing files that changed from the base of the PR and between b5dfaaf and 8437977.

📒 Files selected for processing (13)
  • src/db/client.ts
  • src/lib/auth.ts
  • src/lib/email/inbound.test.ts
  • src/lib/email/inbound.ts
  • src/lib/email/inboxes.test.ts
  • src/lib/email/inboxes.ts
  • src/lib/email/outbound.test.ts
  • src/lib/email/outbound.ts
  • src/lib/email/test-harness.test.ts
  • src/lib/runtime.ts
  • src/orpc/procedures/inboxes.ts
  • src/orpc/procedures/messages.ts
  • src/worker.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/orpc/procedures/messages.ts

@KMKoushik
KMKoushik merged commit 250a149 into main Mar 8, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant